CMAKE_MINIMUM_REQUIRED(VERSION 3.14)

IF (NOT TARGET RPCProto)
    MESSAGE(FATAL_ERROR "Codes using RPC framework must be added after RPC.")
ENDIF()

FIND_PACKAGE(protobuf CONFIG REQUIRED)
FIND_PACKAGE(gRPC CONFIG REQUIRED)
FIND_PACKAGE(Threads)

FUNCTION(ADD_PROTO_FILES FileList)
    STRING(RANDOM LENGTH 8 RANDOM_LIBRARY_NAME)
    ADD_LIBRARY(${RANDOM_LIBRARY_NAME} STATIC ${FileList})

    TARGET_LINK_LIBRARIES(${RANDOM_LIBRARY_NAME}
            PUBLIC
            protobuf::libprotobuf
            gRPC::grpc
            gRPC::grpc++
    )
    TARGET_INCLUDE_DIRECTORIES(${RANDOM_LIBRARY_NAME} PUBLIC ${CMAKE_CURRENT_BINARY_DIR})

    GET_TARGET_PROPERTY(grpc_cpp_plugin_location gRPC::grpc_cpp_plugin LOCATION)
    PROTOBUF_GENERATE(TARGET ${RANDOM_LIBRARY_NAME} LANGUAGE cpp)
    PROTOBUF_GENERATE(TARGET ${RANDOM_LIBRARY_NAME} LANGUAGE grpc GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc PLUGIN "protoc-gen-grpc=${grpc_cpp_plugin_location}")

    TARGET_LINK_LIBRARIES(RPCProto PUBLIC ${RANDOM_LIBRARY_NAME})
ENDFUNCTION()
